import SwiftUI
import BSImageView
import BSImagePicker
import BSGridCollectionViewLayout

struct SwiftUIView: View {
    @State private var image: Image?
    @State private var showingImagePicker = false
    @State private var inputImage: UIImage?

    var body: some View {
        VStack {
            image?
                .resizable()
                .scaledToFit()
                .frame(height: 320)

            Button("Select Image") {
                self.showingImagePicker = true
            }
            
            Button("Save Image") {
//                saveImage()
                let vc = BSImagePickerViewController()
//                bs_presentImagePickerController(vc, animated: true,
//                    select: { (asset: PHAsset) -> Void in
//                      // User selected an asset.
//                      // Do something with it, start upload perhaps?
//                    }, deselect: { (asset: PHAsset) -> Void in
//                      // User deselected an assets.
//                      // Do something, cancel upload?
//                    }, cancel: { (assets: [PHAsset]) -> Void in
//                      // User cancelled. And this where the assets currently selected.
//                    }, finish: { (assets: [PHAsset]) -> Void in
//                      // User finished with these assets
//                }, completion: nil)
                
            }
        }
        .sheet(isPresented: $showingImagePicker, onDismiss: loadImage) {
            ImagePicker(image: self.$inputImage)
        }
    }

    func loadImage() {
        guard let inputImage = inputImage else {
            return
        }
        image = Image(uiImage: inputImage)
    }
    
    func saveImage() {
        inputImage = UIImage(named: "background1")
        let imageSaver = ImageSaver()
        imageSaver.writeToPhotoAlbum(image: inputImage!)
    }
}

struct ImagePicker: UIViewControllerRepresentable {
    @Binding var image: UIImage?
    @Environment(\.presentationMode) var presentationMode

    // 协调器
    class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

        var parent: ImagePicker
        
        // 初始化成员变量
        init(_ parent: ImagePicker) {
            self.parent = parent
        }

        func imagePickerController(
            _ picker: UIImagePickerController, didFinishPickingMediaWithInfo
                info: [UIImagePickerController.InfoKey : Any]) {
            // 选中图片
            if let uiImage = info[.originalImage] as? UIImage {
                parent.image = uiImage
            }
            //
            parent.presentationMode.wrappedValue.dismiss()
//            print(parent.presentationMode)
        }
    }

    // 创建协调器
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    func makeUIViewController(
        context: UIViewControllerRepresentableContext<ImagePicker>) -> UIImagePickerController {
        
        let picker = UIImagePickerController()
        picker.delegate = context.coordinator
        return picker
    }

    func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<ImagePicker>) {

    }
}

class ImageSaver: NSObject {
    func writeToPhotoAlbum(image: UIImage) {
        UIImageWriteToSavedPhotosAlbum(image, self, #selector(saveError), nil)
    }

    @objc func saveError(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
        print("Save finished!")
    }
}



//import SwiftUI
//
//struct SwiftUIView: View {
//
//    @State var isShowPicker: Bool = false
//    @State var image: Image? = Image("placeholder")
//
//    var body: some View {
//        NavigationView {
//            ZStack {
//                VStack {
//                    image?
//                        .resizable()
//                        .scaledToFit()
//                        .frame(height: 320)
//                    Button(action: {
//                        withAnimation {
//                            self.isShowPicker.toggle()
//                        }
//                    }) {
//                        Image(systemName: "photo")
//                            .font(.headline)
//                        Text("IMPORT").font(.headline)
//                    }.foregroundColor(.black)
//                    Spacer()
//                }
//            }
//            .sheet(isPresented: $isShowPicker) {
//                ImagePicker(image: self.$image)
//            }
//            .navigationBarTitle("Pick Image")
//        }
//    }
//}
//
//
//struct ImagePicker: UIViewControllerRepresentable {
//
//    @Environment(\.presentationMode)
//    var presentationMode
//
//    @Binding var image: Image?
//
//    class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
//
//        @Binding var presentationMode: PresentationMode
//        @Binding var image: Image?
//
//        init(presentationMode: Binding<PresentationMode>, image: Binding<Image?>) {
//            _presentationMode = presentationMode
//            _image = image
//        }
//
//        func imagePickerController(_ picker: UIImagePickerController,
//                                   didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
//            let uiImage = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
//            image = Image(uiImage: uiImage)
//            presentationMode.dismiss()
//
//        }
//
//        func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
//            presentationMode.dismiss()
//        }
//
//    }
//
//    func makeCoordinator() -> Coordinator {
//        return Coordinator(presentationMode: presentationMode, image: $image)
//    }
//
//    func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> UIImagePickerController {
//        let picker = UIImagePickerController()
//        picker.delegate = context.coordinator
//        return picker
//    }
//
//    func updateUIViewController(_ uiViewController: UIImagePickerController,
//                                context: UIViewControllerRepresentableContext<ImagePicker>) {
//
//    }
//
//}
//

struct ImgView_Previews: PreviewProvider {
    static var previews: some View {
        NavigationView {
            SwiftUIView()
        }
    }
}
